import { defineStore } from "pinia";

type Theme = "light" | "dark" | "system";
const THEME_KEY = "theme";
const VALID_THEMES: Theme[] = ["light", "dark", "system"];

export const useThemeStore = defineStore("theme", {
  state: () => ({
    theme: "light" as Theme,
    themeColor: "#fff",
  }),
  getters:{
    
  },
  actions: { 
    // 初始化主题
    initTheme() {
      this.theme = this.getInitialTheme();
      this._applyThemeToDom(this.theme);
    },
    /**
     * 安全获取初始主题（从 localStorage）
     */
    getInitialTheme(): Theme {
      const savedTheme = localStorage.getItem(THEME_KEY);
      return VALID_THEMES.includes(savedTheme as Theme) 
        ? savedTheme as Theme 
        : "light";
    },

    /**
     * 切换主题（无参数时切换，有参数时设置为指定主题）
     * @param newTheme 可选参数，指定要设置的主题
     */
    toggleTheme(newTheme?: Theme) {
      const targetTheme = newTheme ?? (this.theme === "light" ? "dark" : "light");
      this.setTheme(targetTheme);
    },

    /**
     * 直接设置主题并同步到 DOM 和存储
     * @param newTheme 要设置的主题
     */
    setTheme(newTheme: Theme) {
      if (!VALID_THEMES.includes(newTheme)) {
        console.warn(`Invalid theme: ${newTheme}`);
        return;
      }

      this.theme = newTheme;
      this._applyThemeToDom(newTheme);
      this._persistTheme(newTheme);
    },

    /**
     * 将主题应用到 DOM
     * @private
     */
     _applyThemeToDom(theme: Theme) {
      document.documentElement.setAttribute("data-theme", theme);
    },

    /**
     * 持久化主题到 localStorage
     * @private
     */
     _persistTheme(theme: Theme) {
      localStorage.setItem(THEME_KEY, theme);
    }
  }
});